package edu.cuit.campus.repository.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/4 9:50
 */
@Slf4j
public class MybatisHelper {
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    static {
        try {
            var reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private MybatisHelper(){

    }

    public static SqlSession openSession(){
        return openSession(false);
    }

    public static SqlSession openSession(boolean autoCommit){
        SqlSession session = tl.get();
        if(session == null){
            session = sqlSessionFactory.openSession(autoCommit);
            tl.set(session);
        }
        return session;
    }

    public static void close(){
        SqlSession session = tl.get();
        if(session != null)
            session.close();
        tl.remove();
    }
}
